var maxDistance = function(arrays) {

  var max = 0;
  var maxIndex=0;
  for(var i=0;i<arrays.length;i++){

    var current = arrays[i].slice(-1)[0]

    if(current>max){
      max=current;
      maxIndex =i;
    }
    if(i+1<arrays.length){

      var nextIndex = i+1
      
      var next = arrays[nextIndex].slice(-1)[0]
      if(max<next){
        max =next
        maxIndex =i+1
      }

    }
  }

  const filterArray = arrays.filter((val,index)=> index!=maxIndex)

  const sortArray = filterArray.sort((a,b)=>a[0]-b[0])

  const min = sortArray[0][0]

  return max-min
    
};

var maxDistance2 = function(arrays){

  const arrayFlat = arrays.flat().sort((a,b)=>b-a)

  const max = arrayFlat[0]

  var maxIndex = 0;

  for(var i=0;i<arrays.length;i++){

    if(arrays[i].includes(max)){
      maxIndex= i;
    }
  }

  const filterArray = arrays.filter((val,index)=> index!=maxIndex)

  const sortArray = filterArray.sort((a,b)=>a[0]-b[0])

  const min = sortArray[0][0]

  return max-min

}

var arrays =[[2,3,4],[1,5,7],[1,3,5],[3,4]]

const res = maxDistance2(arrays)

console.log(res)